<script setup lang="ts">
import type { CompanyVO } from '#/api/company/manage/model';

import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
// import { IconifyIcon } from '@vben/icons';
import { VbenIcon } from '@vben/icons';
import { getVxePopupContainer } from '@vben/utils';

import { CopyOutlined, RedoOutlined } from '@ant-design/icons-vue';
import { useClipboard } from '@vueuse/core';
import {
  Anchor,
  Card,
  Empty,
  message,
  Popconfirm,
  Skeleton,
  Space,
  TabPane,
  Tabs,
} from 'ant-design-vue';

import { companyInfo, companyUnlock } from '#/api/company/manage';
import { ColorTag } from '#/components/dict';
import DetailsDescriptions from '#/components/modal/src/details-descriptions.vue';

import companyDrawer from './company-drawer.vue';
import BusinessInfoTable from './components/business-info-table.vue';
import EmployeeNetworkTable from './components/employee-network-table.vue';
import FollowRecordsTable from './components/follow-records-table.vue';
import GroupMemberTable from './components/group-member-table.vue';
import {
  basicInfoSchema,
  businessInfoSchema,
  listingInfoSchema,
} from './details';

defineOptions({
  name: 'CompanyDetails',
  inheritAttrs: false,
});

const props = defineProps<{ companyId?: any }>();

const { hasAccessByCodes } = useAccess();
const company = ref<CompanyVO>();
const loading = ref(false);
const tabKey = ref<string>('1');

const { setTabTitle } = useTabs();

async function handleLoadInfo(id: any, msg: boolean = false) {
  try {
    if (!id) return null;
    loading.value = true;
    const details = await companyInfo(id);
    if (details) {
      company.value = details;
      setTabTitle(`企业详情：${details.name}`);
    }
    if (msg) {
      message.success('刷新成功');
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

/**
 * 不加legacy在本地开发没有问题
 * 打包后在一些设备会无法复制 使用legacy来保证兼容性
 */
const { copy } = useClipboard({ legacy: true });

async function handleCopy(text: string) {
  await copy(text);
  message.success('复制成功');
}

watch([props.companyId], async (id: any) => {
  if (id) {
    await handleLoadInfo(id);
  }
});

const [CompanyDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: companyDrawer,
});

// 修改
async function handleEdit() {
  drawerApi.setData({ id: company.value?.id });
  drawerApi.open();
}

// 解锁
async function handleUnlock(company: CompanyVO) {
  await companyUnlock(company.id);
  await handleLoadInfo(company.id);
}

// 锚点事件
const anchors = computed(() => {
  const items = [{ key: 'desc1', href: `#desc1`, title: '人工录入信息' }];
  if (company.value?.tycCompany) {
    items.push(
      { key: 'desc2', href: `#desc2`, title: '工商信息' },
      {
        key: 'desc3',
        href: `#desc3`,
        title: '上市信息',
      },
    );
  }
  return items;
});

function handleAnchorClick(e: any, link: any) {
  e.preventDefault();
  if (link?.href) {
    const el = document.querySelector(link.href);
    el?.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }
}

const route = useRoute();
onMounted(() => {
  handleLoadInfo(route.params.id as string);
});
</script>

<template>
  <Page class="basic-info">
    <Skeleton v-show="loading" :paragraph="{ rows: 6 }" active />
    <Card
      v-if="company"
      :body-style="{ overflowY: 'auto', height: '100%' }"
      :loading="loading"
      class="thin-scrollbar flex-1 overflow-y-hidden"
      size="small"
    >
      <!--<template #extra>-->
      <!--  <a-button size="small" @click="() => handleLoadInfo(company.id)">-->
      <!--    <div class="flex items-center justify-center">-->
      <!--    </div>-->
      <!--  </a-button>-->
      <!--</template>-->
      <template v-if="company">
        <!--<template #title>-->
        <!--  <div class="flex items-center gap-2">-->
        <!--    <div>编号: {{ company.id }}</div>-->
        <!--    <CopyOutlined-->
        <!--      class="cursor-pointer"-->
        <!--      @click="handleCopy(company.id)"-->
        <!--    />-->
        <!--  </div>-->
        <!--</template>-->
        <div class="flex flex-col gap-5 p-4">
          <div class="flex flex-col gap-3">
            <div class="flex items-center gap-2">
              <div class="text-2xl font-bold">{{ company.name }}</div>
              <span>
                <CopyOutlined
                  class="cursor-pointer"
                  title="复制"
                  @click="handleCopy(company.name)"
                />
              </span>
            </div>
            <!--<div class="flex items-center gap-2">-->
            <!--  <div class="flex items-center opacity-50">-->
            <!--    <div class="flex items-center gap-1">-->
            <!--      更新时间: {{ company.updateTime }}-->
            <!--    </div>-->
            <!--  </div>-->
            <!--</div>-->
          </div>
          <Tabs v-model:active-key="tabKey" class="flex-1" type="card">
            <TabPane key="1">
              <template #tab>
                <span class="flex items-center gap-1">
                  <VbenIcon
                    class="inline-block"
                    icon="ix:info-multiple"
                  />基本信息
                </span>
              </template>
              <div class="flex items-start justify-center gap-2">
                <div class="flex-1">
                  <DetailsDescriptions
                    id="desc1"
                    title="人工录入信息"
                    class="mb-[50px] mt-[20px]"
                    :columns="basicInfoSchema()"
                    :column="2"
                    :details="company"
                  >
                    <template #extra>
                      <Space>
                        <a-button
                          v-access:code="['company:manager:edit']"
                          @click="handleEdit"
                        >
                          修改信息
                        </a-button>
                        <Popconfirm
                          :get-popup-container="getVxePopupContainer"
                          placement="left"
                          title="确定解锁？"
                          @confirm="handleUnlock(company)"
                        >
                          <a-button
                            v-if="
                              hasAccessByCodes(['company:manager:unlock']) &&
                              !company.tycCompanyId &&
                              company.certificationStatus === 1
                            "
                            type="primary"
                          >
                            解锁
                          </a-button>
                        </Popconfirm>
                        <a-button @click="handleLoadInfo(company.id, true)">
                          <RedoOutlined />
                        </a-button>
                      </Space>
                    </template>
                    <template #labels="{ info }">
                      <div
                        v-if="info.labels.length > 0"
                        class="flex flex-wrap gap-1"
                      >
                        <ColorTag
                          v-for="tag in info.labels"
                          :key="tag.id"
                          :color="tag.listClass"
                          :label="tag.name"
                          :disabled="tag.status === '1'"
                        />
                      </div>
                      <div v-else class="p-5">
                        <Empty description="暂无标签" />
                      </div>
                    </template>
                  </DetailsDescriptions>
                  <DetailsDescriptions
                    v-if="company.tycCompany"
                    id="desc2"
                    title="工商信息"
                    class="mb-[50px]"
                    :columns="businessInfoSchema()"
                    :column="2"
                    :details="company.tycCompany"
                    :show-extra-info="false"
                  />
                  <DetailsDescriptions
                    v-if="company.tycCompany"
                    id="desc3"
                    title="上市信息"
                    class="mb-[50px]"
                    :columns="listingInfoSchema()"
                    :column="2"
                    :details="company.tycCompany"
                    :show-extra-info="false"
                  />
                </div>
                <div class="mt-[80px]">
                  <Anchor
                    affix
                    :offset-top="200"
                    :items="anchors"
                    @click="handleAnchorClick"
                  />
                </div>
              </div>
            </TabPane>
            <TabPane key="2">
              <template #tab>
                <span class="flex items-center gap-1">
                  <VbenIcon
                    class="inline-block"
                    icon="streamline-ultimate:performance-increase"
                  />经营信息
                </span>
              </template>
              <BusinessInfoTable :tyc-company-id="company.tycCompanyId" />
            </TabPane>
            <TabPane key="3">
              <template #tab>
                <span class="flex items-center gap-1">
                  <VbenIcon
                    class="inline-block"
                    icon="eos-icons:organization-outlined"
                  />集团成员
                </span>
              </template>
              <GroupMemberTable
                :tyc-company-id="company.tycCompanyId"
                :group-uuid="company.groupUuid"
              />
            </TabPane>
            <TabPane key="4">
              <template #tab>
                <span class="flex items-center gap-1">
                  <VbenIcon
                    class="inline-block"
                    icon="tabler:users-group"
                  />员工人脉
                </span>
              </template>
              <EmployeeNetworkTable :company-id="company.id" />
            </TabPane>
            <TabPane key="5">
              <template #tab>
                <span class="flex items-center gap-1">
                  <VbenIcon
                    class="inline-block"
                    icon="streamline-ultimate:following-1"
                  />跟进记录
                </span>
              </template>
              <FollowRecordsTable :tyc-company-id="company.tycCompanyId" />
            </TabPane>
          </Tabs>
        </div>
        <!-- 固定底部 -->
        <div class="h-[57px]"></div>
        <div
          v-if="tabKey === '1'"
          class="border-t-solid bg-background absolute bottom-0 left-0 w-full border-t-[1px] p-3 pb-[50px]"
        >
          <div class="flex justify-end">
            <Space>
              <a-button
                v-access:code="['company:manager:edit']"
                @click="handleEdit"
              >
                修改信息
              </a-button>
              <Popconfirm
                :get-popup-container="getVxePopupContainer"
                placement="left"
                title="确定解锁？"
                @confirm="handleUnlock(company)"
              >
                <a-button
                  v-if="
                    hasAccessByCodes(['company:manager:unlock']) &&
                    !company.tycCompanyId &&
                    company.certificationStatus === 1
                  "
                  type="primary"
                >
                  解锁
                </a-button>
              </Popconfirm>
            </Space>
          </div>
        </div>
      </template>
    </Card>
    <CompanyDrawer @reload="handleLoadInfo(company?.id)" />
  </Page>
</template>

<style lang="scss" scoped>
.ant-affix {
  top: 300px !important;
}
</style>
